package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApCollection;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.IApCollectionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.dto.ApCollectionDto;
import com.heima.article.entity.ApCollection;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.IApCollectionService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP收藏信息表 服务实现类
 * </p>
 *
 * @author fpp
 * @since 2022-04-19
 */
@Service
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements IApCollectionService {

    @Override
    public ResponseResult<ApCollection> isCollection(ApCollectionDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        Long articleId = dto.getArticleId();
        LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
        query.eq(ApCollection::getArticleId, articleId);
        query.eq(ApCollection::getEntryId, user.getUserId());
        ApCollection one = this.getOne(query);
        if (dto.getOperation() == 0) {
            if (one == null) {
                one = new ApCollection();
                one.setCollectionTime(new Date());
                one.setArticleId(articleId);
                one.setEntryId(user.getUserId());
                this.save(one);
            }
        } else {
            if (one != null) {
                this.remove(query);
            }
        }
        return ResponseResult.okResult(one);
    }

}
